<?php

namespace app\api\controller\shop;


use app\admin\model\Shopcoupon;
use app\admin\model\Shopdiscount;
use app\admin\model\Shoproom;
use app\admin\model\Useragent;
use app\admin\model\Usercoupon;
use app\admin\model\Userdiscount;
use app\common\controller\Api;
use fast\Http;
use OSS\OssClient;

/**
 *
 */
class Discount extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function add(){

        $type = $this->request->param('type');
        $shop_id = $this->request->param('shop_id');
        $name = $this->request->param('name');
        $startTime = $this->request->param('startTime');
        $endTime = $this->request->param('endTime');
        $max_count = $this->request->param('num');
        $valid_day = $this->request->param('valid_day');
        $discountType = $this->request->param('discountType');
        $discountValue = $this->request->param('discountValue');
        $room = $this->request->param('room');
        $week = $this->request->param('week');
        $valid_time = $this->request->param('valid_time');

        $room = json_decode(htmlspecialchars_decode($room), true);
        $week = json_decode(htmlspecialchars_decode($week), true);


        $shopDiscountModel = new Shopdiscount();
        $coupon = $shopDiscountModel->where('shop_id',$shop_id)->where('type',$type)->where("valid_time",'<',time())->find();
        if($coupon){
            if($type == '新人折扣券'){
                $this->error("您已添加了新人折扣券，只需要添加一张即可");
            }
        }
        $rooms = array();
        foreach ($room as $key => $val) {

            $rooms[] = $val['id'];
        }

        $newWeek = array();
        foreach ($week as $key => $val) {

            if ($val['name'] == "一") {
                $newWeek[] = 1;
            }
            if ($val['name'] == "二") {
                $newWeek[] = 2;
            }
            if ($val['name'] == "三") {
                $newWeek[] = 3;
            }
            if ($val['name'] == "四") {
                $newWeek[] = 4;
            }
            if ($val['name'] == "五") {
                $newWeek[] = 5;
            }
            if ($val['name'] == "六") {
                $newWeek[] = 6;
            }
            if ($val['name'] == "日") {
                $newWeek[] = 7;
            }
        }




        $rule = array();
        $rule['room'] = $rooms;
        $rule['week'] = $newWeek;
        $rule['time'] = $startTime."~".$endTime;

        if($max_count== "") $max_count = 1;

        if($discountType == "折扣抵扣"){
            if($discountValue <0 || $discountValue >=10){
                $this->error("折扣值在1~10之间 不能等于10");
            }
        }

        $db = array();
        $db['name'] = $name;
        $db['type'] = $type;
        $db['discount_type'] = $discountType;
        $db['discount_val'] = $discountValue;
        $db['shop_id'] = $shop_id;
        $db['type'] = $type;
        $db['take_valid_day'] = $valid_day;
        $db['create_time'] = time();
        $db['total'] = $max_count;
        $db['rule'] = json_encode($rule);
        $db['valid_time'] = strtotime($valid_time);

        $shopCouponModel = new Shopdiscount();
        $shopCouponModel->insert($db);
        $this->success('');
    }

    public function getList(){

        $shop_id = $this->request->param('shop_id');
        $shopCouponModel = new Shopdiscount();
        $list = $shopCouponModel->where('shop_id',$shop_id)->where('status','on')->select();

        $shopRoomModel = new Shoproom();
        $shopModel = new \app\admin\model\Shop();
        foreach ($list as $key=>$val){

            $list[$key]['name'] = $val['name'];
            $list[$key]['check'] = false;

            $o = array();
            $o['name'] = "使用时间：".json_decode($val['rule'],true)['time'];
            $tag[] = $o;

            $week = json_decode($val['rule'],true)['week'];
            $w = "";
            foreach ($week as $k=>$v){
                $w .= "周".$v;
                if ($k != count($week) - 1) {
                    $w .= ",";
                }
            }
            $o = array();
            $o['name'] = "使用日期:".$w;
            $tag[] = $o;

            $room = json_decode($val['rule'],true)['room'];

            $rooms = array();
            foreach ($room as $k=>$v){
               $obj = array();
               $r =  $shopRoomModel->where('id',$v)->find();
               $s = $shopModel->where('id',$r['shop_id'])->find();
               $obj['shop_name'] = $s['name'];
               $obj['room_name'] = $r['name'];
               $rooms[] = $obj;
            }

            $list[$key]['rooms'] = $rooms;
        }
        $this->success('',$list);
    }

    public function closeDiscount(){
        $id = $this->request->param('tuan_id');
        $shopCouponModel = new Shopdiscount();
        $shopCouponModel->where('id',$id)->update(['status'=>'off']);

        $this->success('成功');
    }



    public function send(){

        $id = $this->request->param('id');
        $mobile = $this->request->param('mobile');
        $shopCouponModel = new Shopcoupon();
        $coupon = $shopCouponModel->where('id',$id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$coupon['shop_id'])->find();

        if($mobile == ''){
            $this->error("手机号不能为空");
        }
        $userModel = new \app\admin\model\User();
        $user = $userModel->where('org_id',$shop['org_id'])->where('mobile',$mobile)->find();
        if(!$user){
           $this->error("用户不存在");
        }

        $endTime = strtotime("+".$coupon['valid_day']." day",time());

        $userCouponModel = new Usercoupon();
        $userCouponModel->insert(['user_id'=>$user['id'],'coupon_id'=>$coupon['id'],'create_time'=>time(),'status'=>'unuse','valid_time'=>$endTime,'create_time'=>time()]);

        $this->success('');
    }


    public function takeList()
    {

        $user = $this->auth->getUser();
        $mobile = $this->request->param('mobile');
        $shop_id = $this->request->param('shop_id');
        $userDiscountModel = new Userdiscount();
        $page = $this->request->param('page');
        $where = array();
        if($mobile != ""){
            $where['user.mobile'] = $mobile;
        }
        $limit = 10;
        $offset = ($page - 1) * $limit;
        $list = $userDiscountModel->with(['discount','user'])->where($where)->where('discount.shop_id',$shop_id)->limit($offset,$limit)->select();

        foreach ($list as $key=>$val){
            $list[$key]['create_time_txt'] = date("Y-m-d",$val['create_time']);
        }


        $this->success('',$list);
    }

    public function detail()
    {

        $id = $this->request->param('id');

        $disCountModel = new Shopdiscount();
        $discount = $disCountModel->where('id',$id)->find();
        if(!$discount) $this->error("折扣券不存在");



        $app_id = "wx4abd56997bacbaee";
        $app_secret = "99bf27ca154e12d05f7b1ef461dab2c5";


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $app_id . "&secret=" . $app_secret;
        $ret = Http::get($url);
        $obj = json_decode($ret, true);
        $token = $obj['access_token'];


        $scene = $discount['id'];

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => 'pages/member/benefit',

        ];
        $name = "qx_shop_discount_" . $discount['id'];
        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);
        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;
        $filename = './uploads/' . $name . '.jpg';

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if ($discount['qr_code'] != '') {
            $url = cdnurl($discount['qr_code'], true);

        } else {
            base64_image_content($img, $filename);

            $per = 0.5;
            list($width, $height) = getimagesize($filename);
            $n_w = $width * $per;
            $n_h = $height * $per;
            $new = imagecreatetruecolor($n_w, $n_h);
            $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
            imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
            imagedestroy($new);
            imagedestroy($img);

            $config = get_addon_config('alioss');
            $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
            $url = $ret['info']['url'];

            $disCountModel->where('id', $id)->update(['qr_code' => "/" . $name . ".jpg"]);

            $url = str_replace("http", "https", $url);
        }

        $result = array();
        $result['id'] = $id;
        $result['name'] = $discount['name'];
        $result['url'] = $url;

        $this->success('',$result);

    }

}
